<template>
  <div class="card-padding">
   <el-form ref="searchRef" :model="searchForm" :rules="rules" 
   :style="{'width': formWidth}" label-width="auto">
    <el-form-item label="时间范围" prop="timeRange">
      <el-date-picker
        v-model="searchForm.timeRange"
        size="large"
        type="datetimerange"
        range-separator="To"
        start-placeholder="Start date"
        end-placeholder="End date"
      />
    </el-form-item>
    <el-form-item label="指令名称" prop="ids">
<!--      <el-select-->
<!--        v-model="searchForm.ids"-->
<!--        multiple-->
<!--        clearable-->
<!--        placeholder="全部"-->
<!--        style="width: 100%"-->
<!--      >-->
<!--        <template #header>-->
<!--          <el-checkbox-->
<!--            v-model="checkAll"-->
<!--            :indeterminate="indeterminate"-->
<!--            @change="handleCheckAll"-->
<!--          >-->
<!--            全选-->
<!--          </el-checkbox>-->
<!--      </template>-->
<!--        <el-option-->
<!--          v-for="item in options"-->
<!--          :key="item.id"-->
<!--          :label="item.id + '-' + item.cmdName"-->
<!--          :value="item.id"-->
<!--        ></el-option>-->
<!--      </el-select>-->
      <el-cascader
          v-model="searchForm.ids"
          :options="options"
          :props="props"
          style="width: 100%"
      ></el-cascader>
    </el-form-item>
    <el-form-item>
      <el-row>
        <el-col :span="24" >
          <SearchButton @click="handleSearch"></SearchButton>
          <ResetButton @click="handleReset"></ResetButton>
        </el-col>
      </el-row>      
    </el-form-item>
   </el-form>
    <el-table 
    :data="cmdData" 
    empty-text="暂无数据"     
    stripe >
      <el-table-column label="时间" prop="timestamp" sortable width="300px"></el-table-column>
      <el-table-column label="ID" prop="id" sortable width="200px">
        <template #default="scope"><el-tag :color="genColor(scope.row.id)">{{ scope.row.id }}</el-tag></template>
      </el-table-column>
      <el-table-column label="名称" prop="name" width="300px"></el-table-column>
      <el-table-column label="参数">
        <template #default="scope">{{ tranlateBytes(scope.row) }}</template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { onBeforeMount, ref } from 'vue'
import SearchButton from '@/components/Buttons/SearchButton.vue'
import ResetButton from '@/components/Buttons/ResetButton.vue'
import { searchCmdApi } from '@/api/search-api.js'
import { fetchTcList } from '@/api/loads-api.js'
import { failedNotify, blendTwoColors, hashFunction, tranlateBytes, deepClone} from '@/comm/index'
import { myColors } from '@/comm/config'
import moment from 'moment'

const formWidth = '600px'
const checkAll = ref(false)
const indeterminate = ref(false)
let cmdData = ref([])
const searchRef = ref(null)
const searchForm = ref({
  timeRange: '',
  ids: []
})
let options = ref([])
const rules = {
  timeRange: [
   { required: true, message: '必填项', trigger: 'blur' }
  ]
}
const props = { expandTrigger: 'hover', multiple: true }

const genColor = (id) => {
  let numbers = id.match(/[1-9]/g)
  numbers = numbers.join("")
  let numStr = numbers
  while(numStr.length < 6) {
    numStr = numStr + '0'
  }
  
  numStr = '#' + numStr
  let cId = hashFunction(parseInt(numbers), 66)
  let res = blendTwoColors(numStr, myColors[cId])
  return res
}
const handleCheckAll = (val) => {
  indeterminate.value = false
  if (val) {
    searchForm.value.ids = options.value.map((_) => _.id)
  } else {
    searchForm.value.ids = []
  }
}
const  handleSearch = async() => {
  await searchRef.value.validate((valid, fields) => {
    if(valid) {
      let start= moment(searchForm.value.timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
      let end= moment(searchForm.value.timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
      let formIds = []
      for ( const idItem of searchForm.value.ids ) {
        formIds.push( idItem[1] )
      }
      const reqJson = { start: start, end: end, ids: formIds }
      searchCmdApi(reqJson, (response) => {
        const resData = response.data.data
        let sortArr = []
        if(resData.cmds !== null) {
          sortArr = resData.cmds
          sortArr.sort( (a, b) => new Date(b['timestamp']) - new Date(a['timestamp']) )
        }
        cmdData.value = sortArr
      }, (error) => {
        console.log("遥测历史数据查询出错:", error)
      })
    } else {
      console.log('error submit!', fields)
    }
  })
  
}
const handleReset = () => {
  searchRef.value.resetFields()
  cleanChart()
}

const searchTms = () => {
  fetchTcList({}, response => {
    let tcList = []
    const allTcls = response.data.data.cmdSheet || []
    for ( const cmdItem of allTcls )   {
      const cmdName = cmdItem.name || ''
      let rootTree = {
        label: cmdName,
        value: -1,
        children: []
      }
      for(let row of cmdItem.cmds){
        let child = {
          label: `${row.id}-${row.cmdName}`,
          value: row.id
        }
        rootTree.children.push(child)
      }
      tcList.push(rootTree)
    }
    options.value = tcList
  }, (error) => {
    failedNotify(error)
  })
}

onBeforeMount(() => {
  searchTms()
})
</script>

<style lang="scss" scoped>

</style>